#!/usr/bin/env bash
# Summary: Reads specified version file if it exists
# Usage: goenv version-file-read <file>
set -e
[ -n "$GOENV_DEBUG" ] && set -x

VERSION_FILE="$1"

if [ ! -f "$VERSION_FILE" ]; then
  exit 1
fi

if [[ "$(basename $VERSION_FILE)" == "go.mod" ]]; then
  expression_prefix=""

  has_toolchain=$(cat $VERSION_FILE | { grep -E "^toolchain[ \\t]*" || true; })
  if [[ -n "$has_toolchain" ]]; then
    expression_prefix="^toolchain[ \\t]*"
  fi

  expression="${expression_prefix}go[ \\t]*[0-9]+\\.[0-9]+(\\.[0-9]+)?(beta|rc)?"

  versions=($(cat $VERSION_FILE | grep -E "${expression}" | sed "s/${expression_prefix}go[ \\t]*//"))
else
  # NOTE: Read the first non-whitespace word from the specified version file.
  # Be careful not to load it whole in case there's something crazy in it.
  IFS="${IFS}"$'\r'
  words=($(cut -b 1-1024 "$VERSION_FILE" | sed -n 's/^[[:space:]]*\([^[:space:]#][^[:space:]]*\).*/\1/p'))

  versions=("${words[@]}")
fi

if [ ! -n "$versions" ]; then
  exit 1
fi

IFS=":"
echo "${versions[*]}"
exit
